/**
 *
 */
package com.cwt_taxi_xa.util;

import android.text.TextUtils;
import android.util.Log;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.SPConstants;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author zr 带日志文件输入的，可控开关的日志调试
 */
public class AppLog {

	private static final String TAG = "AppLog.";
	private static Boolean MYLOG_SWITCH = true; // 日志文件总开关----------------------------------------------------------
	private static Boolean MYLOG_WRITE_TO_FILE = false;// 日志写入文件开关--------------------------------------------------

	private static char MYLOG_TYPE = 'v';// 输入日志类型，w代表只输出告警信息等，v代表输出所有信息
	private static String MYLOG_PATH_SDCARD_DIR = Constants.LogPath;// 日志文件在sdcard中的路径
	// private static String MYLOG_PATH_RAM_DIR = Constants.RAM_PATH +
	// "dssApp/";// 日志文件在sdcard中的路径
	private static int SDCARD_LOG_FILE_SAVE_DAYS = 0;// sd卡中日志文件的最多保存天数
	private static String MYLOGFILEName = "cwtAppLog.txt";// 本类输出的日志文件名称

	private static SimpleDateFormat myLogSdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");// 日志的输出格式
	private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd");// 日志文件格式

	public static String customTagPrefix = "[MyLog]";

	public static String generateTag() {
		StackTraceElement caller = new Throwable().getStackTrace()[2];
		String tag = "%s.%s(L:%d)";
		String callerClazzName = caller.getClassName();
		callerClazzName = callerClazzName.substring(callerClazzName
				.lastIndexOf(".") + 1);
		tag = String.format(tag, callerClazzName, caller.getMethodName(),
				caller.getLineNumber());
		tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":"
				+ tag;
		return tag;
	}

	public static String generateTag(int index) {
		StackTraceElement caller = new Throwable().getStackTrace()[index];
		String tag = "%s.%s(L:%d)";
		String callerClazzName = caller.getClassName();
		callerClazzName = callerClazzName.substring(callerClazzName
				.lastIndexOf(".") + 1);
		tag = String.format(tag, callerClazzName, caller.getMethodName(),
				caller.getLineNumber());
		tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":"
				+ tag;
		return tag;
	}

	public static void w(Object msg) { // 警告信息
		log(generateTag(), msg.toString(), 'w');
	}

	public static void e(Object msg) { // 错误信息
		log(generateTag(), msg.toString(), 'e');
	}

	public static void d(Object msg) {// 调试信息
		log(generateTag(), msg.toString(), 'd');
	}

	public static void i(Object msg) {//
		log(generateTag(), msg.toString(), 'i');
	}

	public static void v(Object msg) {
		log(generateTag(), msg.toString(), 'v');
	}

	public static void w(String text) {
		log(generateTag(), text, 'w');
	}

	public static void e(String text) {
		log(generateTag(), text, 'e');
	}

	public static void d(String text) {
		log(generateTag(), text, 'd');
	}

	public static void i(String text) {
		log(generateTag(), text, 'i');
	}

	public static void v(String text) {
		log(generateTag(), text, 'v');
	}

	public static void w(String tag, Object msg) { // 警告信息
		log(tag, msg.toString(), 'w');
	}

	public static void e(String tag, Object msg) { // 错误信息
		log(tag, msg.toString(), 'e');
	}

	public static void d(String tag, Object msg) {// 调试信息
		log(tag, msg.toString(), 'd');
	}

	public static void i(String tag, Object msg) {//
		log(tag, msg.toString(), 'i');
	}

	public static void v(String tag, Object msg) {
		log(tag, msg.toString(), 'v');
	}

	public static void w(String tag, String text) {
		log(tag, text, 'w');
	}

	public static void e(String tag, String text) {
		log(tag, text, 'e');
	}

	public static void d(String tag, String text) {
		log(tag, text, 'd');
	}

	public static void i(String tag, String text) {
		log(tag, text, 'i');
	}

	public static void v(String tag, String text) {
		log(tag, text, 'v');
	}

	/**
	 * 根据tag, msg和等级，输出日志
	 *
	 * @param tag
	 * @param msg
	 * @param level
	 * @return void
	 * @since v 1.0
	 */
	private static void log(String tag, String msg, char level) {

		try {
			if (MYLOG_SWITCH) {
				if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // 输出错误信息
					Log.e(tag, msg);
				} else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
					Log.w(tag, msg);
				} else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
					Log.d(tag, msg);
				} else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
					Log.i(tag, msg);
				} else {
					Log.v(tag, msg);
				}
				if (MYLOG_WRITE_TO_FILE) {
//					writeLogtoFile(String.valueOf(level), tag, msg);
				}
				/*
				 * if(SplashScreen.inProcess){
				 * writeLogToMemory(String.valueOf(level), tag, msg); }
				 */
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void writeLogToMemory(String level, String tag, String msg) {
		// TODO Auto-generated method stub
		Date nowtime = new Date();
		String needWriteFiel = logfile.format(nowtime);
		String needWriteMessage = "[" + myLogSdf.format(nowtime) + "]    "
				+ level + "    " + tag + "    " + msg;

		// 检查文件路径是否存在
		File filePath = new File(MYLOG_PATH_SDCARD_DIR);
		if (!filePath.exists()) {
			filePath.mkdir();
		}

		File file = new File(MYLOG_PATH_SDCARD_DIR, needWriteFiel
				+ MYLOGFILEName);

		try {
			FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
			BufferedWriter bufWriter = new BufferedWriter(filerWriter);
			bufWriter.write(needWriteMessage);
			bufWriter.newLine();
			bufWriter.close();
			filerWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}
	}

	/**
	 * 打开日志文件并写入日志
	 *
	 * @return
	 * **/
	private static void writeLogtoFile(String mylogtype, String tag, String text) {// 新建或打开日志文件

		try {
			long sdsize = FileOper.getSDAllSize(Constants.SDPath);
			if (sdsize < 20) {
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e));
		}


		Date nowtime = new Date();
		String needWriteFiel = logfile.format(nowtime);
		String needWriteMessage = "[" + myLogSdf.format(nowtime) + "]    "
				+ mylogtype + "    " + tag + "    " + text;

		// 检查文件路径是否存在
		File filePath = new File(MYLOG_PATH_SDCARD_DIR);
		if (!filePath.exists()) {
			filePath.mkdir();
		}

		// 检查文件路径是否存在
		filePath = new File(MYLOG_PATH_SDCARD_DIR + "log/");
		if (!filePath.exists()) {
			filePath.mkdir();
		}

		File file = new File(MYLOG_PATH_SDCARD_DIR + "log/", needWriteFiel
				+ MYLOGFILEName);

		try {
			FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
			BufferedWriter bufWriter = new BufferedWriter(filerWriter);
			bufWriter.write(needWriteMessage);
			bufWriter.newLine();
			bufWriter.close();
			filerWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}
	}

	/**
	 * 删除制定的日志文件
	 * */
	public static void delFile() {// 删除日志文件
		String needDelFiel = logfile.format(getDateBefore());
		File file = new File(MYLOG_PATH_SDCARD_DIR, needDelFiel + MYLOGFILEName);
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 得到现在时间前的几天日期，用来得到需要删除的日志文件名
	 * */
	private static Date getDateBefore() {
		Date nowtime = new Date();
		Calendar now = Calendar.getInstance();
		now.setTime(nowtime);
		now.set(Calendar.DATE, now.get(Calendar.DATE)
				- SDCARD_LOG_FILE_SAVE_DAYS);
		return now.getTime();
	}





	static File f_pc;
	static FileOutputStream fos_pc;
	public static void saveFile(byte[] data, boolean end, int id){
		try {
			if(!end){
				if(f_pc==null||!f_pc.exists()){
					f_pc = new File("/mnt/sdcard/testFile"+id+".jpg");
					if(f_pc.exists()) f_pc.delete();
					fos_pc = new FileOutputStream(f_pc);
				}
				fos_pc.write(data);
				fos_pc.flush();
			}else{
				fos_pc.close();
				fos_pc = null;
				FileInputStream in = new FileInputStream(f_pc);
				byte[] filedata = new byte[(int) f_pc.length()];
				in.read(filedata);
				fos_pc = new FileOutputStream(f_pc);
				int size00 = 0;
				for (int i = 0; i < filedata.length; i++) {
					if(filedata[filedata.length-1-i]==0x00){
						size00++;
					}else{
						break;
					}
				}
				AppLog.e(""+size00);
				byte[] filedata2 = new byte[filedata.length-size00-2];
				System.arraycopy(filedata, 2, filedata2, 0, filedata2.length);
				fos_pc.write(filedata2);
				fos_pc.flush();
				fos_pc.close();
				MainApplication.topActivity.sendMsg(id, f_pc.getAbsolutePath());
				f_pc = null;
				fos_pc = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void saveFile_clear(){
		if(f_pc!=null){
			if(f_pc.exists()){
				f_pc.delete();
			}
			f_pc = null;
		}
	}





	static File f;
	static FileOutputStream fos;
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
	public static void saveTxt(String str){
		if(!SPConstants.log_test) return;
		try {
			if(f==null||!f.exists()){
				f = new File("/mnt/sdcard/APPLog-"+sdf.format(new Date())+".txt");
				fos = new FileOutputStream(f);
			}
			fos.write("\n".getBytes());
			fos.write((sdf.format(new Date())+"\n").getBytes());
			fos.write((str+"\n").getBytes());
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void saveTxt_s6(String str){
		try {
			if(f==null||!f.exists()){
				f = new File("/mnt/sdcard/APPLog-"+sdf.format(new Date())+".txt");
				fos = new FileOutputStream(f);
			}
			fos.write("\n".getBytes());
			fos.write((sdf.format(new Date())+"\n").getBytes());
			fos.write((str+"\n").getBytes());
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void saveTxt2(String str){
//		try {
//			if(f==null||!f.exists()){
//				f = new File("/mnt/sdcard/APPLog-"+sdf.format(new Date())+".txt");
//				fos = new FileOutputStream(f);
//			}
//			fos.write("\n".getBytes());
//			fos.write((sdf.format(new Date())+"\n").getBytes());
//			fos.write((str+"\n").getBytes());
//			fos.flush();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}




	/**
	 * 保存长篇日志文件
	 */
	static File file_debug;
	static FileOutputStream fos_debug;
	static String path_debug = "/mnt/sdcard/导航终端日志文件/";
	static long maxleng = 1024*1024*50;
	public static synchronized void savelog(String str){


		CatchLogUtils.saveLog(str, new Date());

//		if(!Constants.debug) return;
//
//		try {
//			//判断输出流
//			if(fos_debug == null){
//				file_debug = new File(path_debug);
//				if(!file_debug.exists()){
//					file_debug.mkdir();
//				}
//				File[] fs = file_debug.listFiles();
//
//				//顺便检查是否清理
//				if(fs.length>10){
//					for (int i = 0; i < fs.length-1; i++) {
//						for (int j = i+1; j < fs.length; j++) {
//							if(fs[i].lastModified() > fs[j].lastModified()){
//								File f = fs[i];
//								fs[i] = fs[j];
//								fs[j] = f;
//							}
////							if(Long.parseLong(fs[i].getName().replace(".txt", "").substring(4)) >
////							Long.parseLong(fs[j].getName().replace(".txt", "").substring(4))){
////								File f = fs[i];
////								fs[i] = fs[j];
////								fs[j] = f;
////							}
//						}
//					}
//					int delecount = fs.length-5;
//					for (int i = 0; i < delecount; i++) {
//						fs[i].delete();
//					}
//					fs = file_debug.listFiles();
//				}
//
//				for (int i = 0; i < fs.length; i++) {
//					if(fs[i].length()<maxleng){
//						file_debug = fs[i];
//						fos_debug = new FileOutputStream(file_debug, true);
//						break;
//					}
//				}
//				if(fos_debug==null){
//					file_debug = new File(file_debug, "LOG-"+System.currentTimeMillis()+".txt");
//					fos_debug = new FileOutputStream(file_debug, true);
//				}
//				fos_debug.write(("\n\n"+sdf.format(new Date())+"   "+generateTag()+"  ---------------------------" +
//						"打开输出流" +
//						"---------------------------").getBytes());
//			}
//
//
//			//写出数据
//			str = "\n\n"+sdf.format(new Date())+"   "+generateTag()+"\n"+str;
//			fos_debug.write(str.getBytes());
//
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			file_debug = null;
//			fos_debug = null;
//		}


	}




}
